﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.ComponentModel;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Linq;
using System.Text;


namespace client
{
    public class SearchService:INotifyPropertyChanged
    {
        public string receivedService;
        public string receivedData;



        public ObservableCollection<RestaurantContent> RestaurantList
        {
            get;
            set;
        }


        public SearchService()
        {
            receivedService = "aaaaa";
            RestaurantList = new ObservableCollection<RestaurantContent>();
        }

        public void getService(string input) 
        {
            Debug.WriteLine(input);
            UriBuilder fullUri = new UriBuilder("http://csci5221group05test.cloudapp.net/ServiceSearch.aspx");
            fullUri.Query = input;
            
            HttpWebRequest dataRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

            // set up the state object for the async request
            DataUpdateState dataState = new DataUpdateState();
            dataState.AsyncRequest = dataRequest;
            dataRequest.BeginGetResponse(new AsyncCallback(HandleDataResponse),
                dataState);
            
        
        }

        private void HandleDataResponse(IAsyncResult asyncResult)
        {
            
            Debug.WriteLine("HandleDataResponse");
            // get the state information
            DataUpdateState dataState = (DataUpdateState)asyncResult.AsyncState;
            HttpWebRequest dataRequest = (HttpWebRequest)dataState.AsyncRequest;


            // end the async request
            dataState.AsyncResponse = (HttpWebResponse)dataRequest.EndGetResponse(asyncResult);

            Stream streamResult;

            ObservableCollection<RestaurantContent> newForecastList =
                     new ObservableCollection<RestaurantContent>();

            try
            {
                streamResult = dataState.AsyncResponse.GetResponseStream();
               StreamReader sr = new StreamReader(streamResult);

                //Debug.WriteLine("UI");
                receivedService = sr.ReadToEnd();
                string xmlData= receivedService.Split('*')[0];
                Debug.WriteLine("=======" + xmlData);
                byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);
                MemoryStream xmlStream = new MemoryStream(byteArray); 
         
                //ObservableCollection<RestaurantContent> newRestaurantList =
                //    new ObservableCollection<RestaurantContent>();

                /* Stream xmlStream= new MemoryStream(1000);
                 StreamWriter sw = new StreamWriter(xmlStream);
                 sw.Write(xmlData);
                 */
                StreamReader sr2 = new StreamReader(xmlStream);

                //Debug.WriteLine("UI");
                string temp = sr2.ReadToEnd();

                Debug.WriteLine("oooooooo" + temp);
                xmlStream.Position = 0;
                XElement xmlRestaurant = XElement.Load(xmlStream);

                
                XElement xmlCurrent = xmlRestaurant.Descendants("Services").First();
                Debug.WriteLine("**01" + xmlCurrent.ToString());
                /*int timeIndex = 1;
                while (xmlCurrent.Elements("Service").Count() < 1)
                {
                    xmlCurrent = xmlRestaurant.Descendants("Services").ElementAt(timeIndex);
                    timeIndex++;
                }*/

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        //Debug.WriteLine(newContent.Name);
                        RestaurantList.Clear();
                        foreach (XElement curElement in xmlCurrent.Elements("Service"))
                        {
                            try
                            {
                                RestaurantContent newContent = new RestaurantContent();
                                newContent.ID = (int)(curElement.Element("ID"));
                                newContent.Name = (string)(curElement.Element("Name"));
                                newContent.Provider = (string)(curElement.Element("Provider"));
                                RestaurantList.Add(newContent);
                            }
                            catch (FormatException)
                            {}
                        }

                    });
            }
            catch(FormatException){}
        }              

           

        public event PropertyChangedEventHandler PropertyChanged;

 /*       public string Result
        {
            get
            {
                return receivedService;
            }
            set
            {
                this.receivedService = value;
                NotifyPropertyChanged("Result");
            }
        }

  */


        public void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
}

